package com.yuanxiao.filter;

import com.yuanxiao.utils.NetworkUtil;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Activate(group = {CommonConstants.CONSUMER})
public class TransportIPFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        System.out.println("++++++++++++++++++>>>>>>>>>>>>>>>>>>>>>>>>>");
        HttpServletRequest request=null;

        try {

            request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }catch (NullPointerException e){
            return invoker.invoke(invocation);
        }
        String ipAddress="";
        try {
            ipAddress = NetworkUtil.getIpAddress(request);
        } catch (IOException e) {
            ipAddress="";
        }
        RpcContext.getContext().setAttachment("clientIp",ipAddress);
        return invoker.invoke(invocation);
    }
}
